﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace CodeContrib.Web.Routing
{
	public static class TenantRouteTable
	{
		private static readonly List<TenantRouteInfo> _tenantRoutes = new List<TenantRouteInfo>();

		private static object SyncRoot
		{
			get { return ((IList)_tenantRoutes).SyncRoot; }
		}

		public static void Add(TenantRouteInfo tenantRoute)
		{
			Guard.NotNull(tenantRoute, "tenantRoute");

			var index = _tenantRoutes.Count();

			lock (SyncRoot)
			{
				for (var i = 0; i < _tenantRoutes.Count; i++)
				{
					var existingtenantRouteInfo = _tenantRoutes[i];

					if (tenantRoute.HasSameHost(existingtenantRouteInfo))
					{
						index = (tenantRoute.HasHigherPriority(existingtenantRouteInfo)) ? i : i + 1;

						break;
					}
				}

				_tenantRoutes.Insert(index, tenantRoute);
			}
		}

		public static TenantRouteInfo Find(Uri uri)
		{
			return _tenantRoutes.Find(d => d.Match(uri));
		}

		public static void Remove(TenantRouteInfo tenantRoute)
		{
			lock (SyncRoot)
			{
				_tenantRoutes.RemoveAll(d => d.TenantId == tenantRoute.TenantId);
			}
		}
	}
}